<template>
	<view class="page-container">
		<scroll-view class="tabs-container" scroll-y :style="'height:' + clentHeight + 'px'">
			<uv-empty v-if="cartItems.length==0" icon="/static/images/default/empty_car.png" text="购物车空空如也"></uv-empty>

			<view v-else v-for="( item,index ) in cartItems" :key="index" class="order-list">
				<view class="order-title">
					<view class="order-head left">
						{{ item.mealType === "商店" ? item.mealType : item.date + " " + item.mealType }}
					</view>
					<view v-if="item.time" class="order-head right">送餐时间：{{ item.time }}</view>
				</view>

				<view v-for="(goods,i) in item.products" :key="goods.id" class="order-contain">
					<uv-checkbox-group>
						<uv-checkbox @change="checkboxChange(index,i)" class="select-checkbox" shape="circle"
							:checked="goods.selected" :name="goods.name" size="20" activeColor="#1975ed">
						</uv-checkbox>
						<view class="order-contain-inner">
							<view class="order-image">
								<image :src="goods.image" mode="aspectFill" class="imgStyle">
							</view>
							<view class="order-text">
								<view class="title">{{ goods.name }}</view>
								<view class="box-inner">
									<view class="price">
										<span class="now">￥{{ ( goods.price * goods.count ).toFixed(2) }}</span>
									</view>
									<view class="cart-control-wrapper">
										<cart-control @add="onAdd($event,item)" :food="goods"
											@decrease="decrease(goods, item)"></cart-control>
									</view>
								</view>
							</view>
						</view>
					</uv-checkbox-group>
				</view>
			</view>
		</scroll-view>
		<view class="navigation" v-if="cartItems.length !== 0">
			<view class="left">
				<view class="item">
					<uv-checkbox-group>
						<uv-checkbox :checked="bigseled" v-model="isSelectedAllRow" :disabled="!cartItems.length"
							shape="circle" @change="selectedAllRow" label="全选" activeColor="#1975ed">
						</uv-checkbox>
					</uv-checkbox-group>
				</view>
				<!-- <view class="item">
					<view class="goods-remove u-line-1" v-if="selectedAllRowLength" @click="removeGoodsEvent">
						<uv-icon name="trash-fill" size="18" color="#888888" label-color="#888888" label="删除"></uv-icon>
					</view>
				</view> -->
			</view>

			<view class="right">
				<view class="total-cost">
					<view v-if="selectedAllRowLength==0">合计<text class="red-price">￥0</text></view>
					<view v-else>
						<view>合计<text class="red-price">￥{{sumPrice}}</text></view>
					</view>
				</view>
				<view class="buy btn u-line-1" @click="goCommon">结算<text
						v-if="selectedAllRowLength">({{selectedAllRowLength}})</text></view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapActions
	} from "vuex";
	import CartControl from '@/component/cart-control'
	import address from "../../store/modules/address";
	export default {
		name: "CartPage",
		components: {
			CartControl
		},
		data() {
			return {
				clentHeight: 0, // 内容块的高度
				isSelectedAllRow: true, // 全选所有商品
				selectedAllRowLength: 0,
				bigseled: true,
				sumPrice: '0.00'
			}
		},
		computed: {
			...mapGetters(["totalCount", "cartItems", "address"])
		},
		watch: {
			// 深度监听 cartItems 的变化
			cartItems: {
				deep: true,
				handler() {
					this.sumTotalPrice(); // 自动重新计算总价和数量
				}
			}
		},
		onReady() {
			// this.getClientHeight();
			// 初步渲染完后执行
			setTimeout(() => {
				uni.getSystemInfo({
					success: res => {
						// 可视区域高度
						console.log('总高度', res.windowHeight);
						const navigationHeight = this.cartItems.length ? 54 : 0;
						this.clentHeight = res.windowHeight - navigationHeight - 0;
						console.log('滚动高度', this.clentHeight);
					}
				});
			})
		},
		created() {
			// 页面加载时清理过期商品
			this.clearExpiredCartItems();
			this.initializeSelection();
			this.sumTotalPrice();
			this.getTotalCount();
		},
		methods: {
			...mapActions(["clearExpiredCartItems", "addCartItems", "decreaseOrderItems"]),

			// 初始化所有商品的选中状态
			initializeSelection() {
				this.cartItems.forEach(item => {
					item.products.forEach(goods => {
						goods.selected = true; // 设置所有商品为选中状态
					});
				});

				this.isSelectedAllRow = true; // 设置全选状态为选中
				this.bigseled = true; // 同步全选按钮的状态
			},

			handleCartAction(action, goods, item) {
				// 延迟计算总价格
				setTimeout(() => {
					this.sumTotalPrice();
				}, 300);
				this.getTotalCount()
			},

			onAdd(goods, item) {
				this.handleCartAction('add', goods, item);

				const payload = {
					date: item.date, // 当前日期
					mealType: item.mealType, // 当前餐类
					time: item.time, // 送餐时间
					products: [] // 存放餐类下的所有产品
				};

				// 假设 item 是一个包含多个产品的对象，每个产品都有 id、image、name、count 等信息
				item.products.forEach(product => {
					// 为每个产品创建一个对应的对象
					const productPayload = {
						id: product.id,
						image: product.image,
						name: product.name,
						selected: product.selected,
						price: product.price,
						count: product.count
					};

					// 将每个产品添加到 products 数组中
					payload.products.push(productPayload);
				});
				this.addCartItems(payload); // 将整个 payload 对象传递给购物车

				// 更新购物车的数量
				this.getTotalCount();
			},

			decrease(goods, item) {
				this.handleCartAction('decrease', goods, item);
				console.log('减少', item);

				// 创建一个新的 payload 对象来传递给购物车
				const payload = {
					date: item.date, // 当前日期
					mealType: item.mealType, // 当前餐类
					time: item.time, // 送餐时间
					products: [] // 存放餐类下的所有产品
				};
				
				this.decreaseOrderItems(payload);
				// 更新购物车的数量
				this.getTotalCount();
			},

			getTotalCount() {
				console.log('this.totalCount', this.totalCount);
				// 更新 tabBarBadge
				if (this.totalCount > 0) {
					uni.setTabBarBadge({
						index: 1, // tabBar 索引
						text: this.totalCount.toString(), // 使用 Vuex 中的商品总数
					});
				} else {
					// 当 totalCount 为 0 时，移除 badge
					uni.removeTabBarBadge({
						index: 1,
					});
				}
			},

			// 单个复选框选中事件
			checkboxChange(m, n) {
				// 检查 cartItems[m] 和 cartItems[m].items 是否存在
				if (this.cartItems[m] && this.cartItems[m].products && this.cartItems[m].products[n]) {
					const goods = this.cartItems[m].products[n]; // 确保 .products 数组存在
					goods.selected = !goods.selected;

					// 更新全选按钮的状态
					this.isSelectedAllRow = this.cartItems.every(item =>
						item.products.every(goods => goods.selected)
					);

					this.bigseled = this.isSelectedAllRow; // 同步全选按钮的状态
					this.sumTotalPrice(); // 更新总价和数量
				} else {
					console.error('Invalid cart item or product at index:', m, n);
				}
			},

			// 全选/取消全选事件
			selectedAllRow() {
				// 判断当前是否已经是全选状态
				const isCurrentlyAllSelected = this.cartItems.every(item =>
					item.products && item.products.every(goods => goods.selected) // 确保 item.products 存在
				);

				// 如果是全选状态，则取消全选；否则设置为全选
				const newSelectionState = !isCurrentlyAllSelected;

				this.cartItems.forEach(item => {
					if (item.products) { // 确保 item.products 存在
						item.products.forEach(goods => {
							goods.selected = newSelectionState; // 更新所有商品的选中状态
						});
					}
				});

				this.isSelectedAllRow = newSelectionState; // 更新全选按钮的状态
				this.bigseled = newSelectionState; // 同步全选状态
				this.sumTotalPrice(); // 更新总价和数量
			},

			/* 获取选择数据 */
			getSelectedInfoList() {
				let len = this.cartItems.length
				this.selectedAllRowList = []
				for (let i = 0; i < len; i++) {
					this.selectedAllRowList.push(i)
				}
				console.log('这是什么', this.selectedAllRowList)
			},

			// 计算所有选中商品的总价格和数量
			sumTotalPrice() {
				let total = 0;
				let count = 0;
				const selectedGoodsList = []; // 用于存储选中的商品

				// 遍历 cartItems，构造选中商品的新结构
				this.cartItems.forEach(item => {
					let itemTotalPrice = 0; // 当前 item 下选中商品的总价
					const selectedProducts = []; // 用于存储当前 item 下的选中商品

					item.products.forEach(goods => {
						if (goods.selected) {
							total += goods.price * goods.count; // 累加价格
							count += goods.count; // 累加数量

							itemTotalPrice += goods.price * goods.count; // 累加当前商品总价

							// 将选中的商品添加到 selectedProducts 数组
							selectedProducts.push({
								id: goods.id,
								name: goods.name,
								price: goods.price,
								count: goods.count,
								image: goods.image,
								selected: goods.selected // 保留选中状态
							});
						}
					});

					// 如果该 item 中有选中的商品，则将 item 的信息和选中的商品一并加入 selectedGoodsList
					if (selectedProducts.length > 0) {
						const discount = 0;
						const deal = (itemTotalPrice - discount).toFixed(2);
						selectedGoodsList.push({
							date: item.date, // 当前日期
							mealType: item.mealType, // 当前餐类
							time: item.time, // 送餐时间
							products: selectedProducts, // 只包含选中的商品
							totalPrice: itemTotalPrice.toFixed(2), // 添加该日期下所有商品的总价
							discount: discount,
							deal: deal
						});
					}
				});

				this.sumPrice = total.toFixed(2); // 总价保留两位小数
				this.selectedAllRowLength = count; // 更新选中商品总数量

				// 将选中的商品列表保存到 Vuex 或其他地方
				this.$store.dispatch('updateSelectedGoodsList', selectedGoodsList);
				this.$store.dispatch('updateSumPrice', this.sumPrice);
				this.$store.dispatch('updateSelectedRowLength', this.selectedAllRowLength);
			},

			goCommon() {
				const address = this.address
				console.log('地址', address)
				if (address != null) {
					// 如果有地址，跳转到结算页面
					uni.navigateTo({
						url: '/pages/takeaway/settlement'
					});
				} else {
					// 如果没有地址，跳转到表单页面
					uni.navigateTo({
						url: '/pages/takeaway/addAddress' // 替换为表单页面的路径
					});
				}
			}
		}
	}
</script>


<style scoped lang="scss">
	.page-container {
		background-color: #f7f7f7;
		overflow: hidden;

		.order-list {
			background-color: #ffffff;
			margin-bottom: 24rpx;
			padding: 24rpx 32rpx 0;
			font-size: 26rpx;
			overflow: hidden;

			.order-title {
				padding-bottom: 24rpx;
				display: flex;
				margin-bottom: 24rpx;

				.order-head {
					flex: 1;

					&.left {
						text-align: left;
					}

					&.right {
						text-align: right;
					}
				}
			}

			.order-contain {
				display: flex;
				margin-bottom: 30rpx;

				.order-contain-inner {
					display: flex;
					align-items: center;
					width: calc(100% - 72rpx);
					align-items: flex-start;
					padding-left: 10px;

					.order-image {
						width: 60px;
						padding-right: 24rpx;

						.imgStyle {
							width: 60px;
							height: 60px;
							border-radius: 12rpx;
							margin-right: 20rpx;
						}
					}

					.order-text {
						flex: 1;
						height: 100%;

						.title {
							font-weight: 600;
							font-size: 28rpx;
							color: #111;
						}

						.box-inner {
							display: flex;
							height: calc(100% - 20px);
							align-items: flex-end;

							.price {
								flex: 1;

								.now {
									margin-right: 8px;
									font-size: 14px;
									color: #ff6506;
									font-weight: 600;
								}

							}

							.cart-control-wrapper {
								text-align: right;
							}
						}
					}
				}
			}
		}

		.navigation {
			display: flex;
			align-items: center;
			justify-content: space-between;
			background-color: #ffffff;
			position: fixed;
			bottom: 50px;
			height: 54px;
			z-index: 3;
			width: 100%;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);


			.left {
				display: flex;
				font-size: 20rpx;
				margin-left: 32rpx;

				.item {
					margin-right: 20rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
				}
			}

			.right {
				display: flex;
				font-size: 28rpx;
				align-items: center;
				margin-right: 20rpx;

				.btn {
					line-height: 66rpx;
					padding: 0 30rpx;
					border-radius: 36rpx;
					color: #ffffff;
				}

				.total-cost {
					margin-right: 30rpx;

					.red-price {
						color: red
					}
				}

				.buy {
					background-color: #ff7900;
				}
			}
		}


	}
</style>